/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/subtree-of-another-tree
   @Language: C++
   @Datetime: 19-05-15 16:19
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	bool judge(TreeNode *s, TreeNode *t){
		if(s==NULL && t==NULL) return true;
		if(s==NULL || t==NULL) return false;
		if(s->val!=t->val) return false;
		return judge(s->left,t->left) && judge(s->right, t->right);
	}
public:
	/**
	 * @param s: the s' root
	 * @param t: the t' root
	 * @return: whether tree t has exactly the same structure and node values with a subtree of s
	 */
	bool isSubtree(TreeNode * s, TreeNode * t) {
		// Write your code here
		queue<TreeNode*> q;
		bool found=false;
		for(q.push(s); !found && q.size(); q.pop()){
			const auto &node=q.front();
			found=judge(node,t);
			if(node->left) q.push(node->left);
			if(node->right) q.push(node->right);
		}
		return found;
	}
};
